package simulation;

import java.awt.geom.Point2D;
import util.Vector;

/**
 * Create center of mass force by extending force class
 * @author Natalia Carvalho
 */
public class CenterOfMassForce extends Force {
    private static Point2D ourCenterOfMass = null;
    private static double ourCumulativeMassTotalX;
    private static double ourCumulativeMassTotalY;
    private static double ourCumulativeMassTotal;
    private double myCenterOfMassMagnitude = 0;
    private double myCenterOfMassExponent = 0;
    private int myIndex;

    /**
     * Constructor for gravity force
     * @param centerOfMassMagnitude is magnitude of center of mass
     * @param centerOfMassExponent is exponent of center of mass
     * @param index of center of mass force
     */
    public CenterOfMassForce(double centerOfMassMagnitude, double centerOfMassExponent, int index) {
        super(index);
        myCenterOfMassMagnitude = centerOfMassMagnitude;
        myCenterOfMassExponent = centerOfMassExponent;
    }
    
    void applyForce (Mass m) {
        if (ourCenterOfMass != null && isActive()) {
            m.applyForce(new Vector(Vector.angleBetween(ourCenterOfMass, m.getPosition()), 
                                    myCenterOfMassMagnitude *
                                    Math.pow(Vector.distanceBetween(m.getPosition(),
                                                                    ourCenterOfMass),
                                             myCenterOfMassExponent)));
        }
        ourCumulativeMassTotalX += m.getPosition().getX() * m.getMass();
        ourCumulativeMassTotalY += m.getPosition().getY() * m.getMass();
        ourCumulativeMassTotal += m.getMass();
    }
    
    /**
     * Resets cumulative mass total
     */
    public static void setCumulativeMassToZero() {
        ourCumulativeMassTotalX = 0;
        ourCumulativeMassTotalY = 0;
        ourCumulativeMassTotal = 0;
    }
    
    /**
     * Calculates point2D ourCenterOfMass
     */
    public static void centerOfMass() {
        if (ourCumulativeMassTotal != 0) {
            ourCenterOfMass = new Point2D.Double(ourCumulativeMassTotalX / ourCumulativeMassTotal, 
                    ourCumulativeMassTotalY / ourCumulativeMassTotal);
        }
    }

    /**
     * Get index
     */
    public int getMyIndex () {
        return myIndex;
    }

    /**
     * Set index
     * @param index is index to be set
     */
    public void setMyIndex (int index) {
        myIndex = index;
    }

}

